package com.haiya.oauth.controller;

import com.google.common.collect.Maps;
import com.haiya.common.request.Query;
import com.haiya.common.response.CommonRes;
import com.haiya.common.response.PageRes;
import com.haiya.oauth.dto.ClientDto;
import com.haiya.oauth.service.IClientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 应用相关接口
 *
 * @author qiaoguoqiang
 */
@Api(tags = "应用")
@RestController
@RequestMapping("/clients")
public class ClientController {
    @Autowired
    private IClientService clientService;

    @GetMapping("/list")
    @ApiOperation(value = "应用列表")
    public CommonRes list(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        return CommonRes.ok(clientService.listClient(query, true));
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id获取应用")
    public CommonRes info(@PathVariable Long id) {
        return CommonRes.ok(clientService.getById(id));
    }

    @GetMapping("/all")
    @ApiOperation(value = "所有应用")
    public CommonRes allClient() {
        Query query = new Query(Maps.newHashMap());
        PageRes pageRes = clientService.listClient(query, false);
        return CommonRes.ok(pageRes.getList());
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除应用")
    public CommonRes delete(@PathVariable Long id) {
        int i = clientService.delClient(id);
        if (i > 0) {
            return CommonRes.ok(i);
        }
        return CommonRes.error();
    }

    /**
     * 新增不传id, 修改传id, 以clientId检查唯一性
     * 发生异常的处理, 比如clientId存在?? com.haiya.common.exception.IdempotencyException: test已存在
     *
     * @param clientDto: clientSecret, clientSecretStr必填字段
     * @return
     * @throws Exception
     */
    @PostMapping("/saveOrUpdate")
    @ApiOperation(value = "保存或者修改应用")
    public CommonRes saveOrUpdate(@RequestBody ClientDto clientDto) throws Exception {
        boolean b = clientService.saveClient(clientDto);
        if (b) {
            return CommonRes.ok();
        } else {
            return CommonRes.error();
        }
    }
}
